package org.dromara.system.utils;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class MaxExcelUtil extends ImportExcelUtil{

    public static List<List<Object>> getListOfDoubleTableSheet(InputStream in, String fileName,String sheetName,String tableName) throws Exception {
        List<List<Object>> list = null;
        //创建Excel工作薄
        Workbook work = MaxExcelUtil.getWorkbook(in,fileName);
        if(work == null){
            throw new Exception("创建Excel工作薄为空！");
        }
        Sheet sheet = null;
        Row row = null;
        Cell cell = null;
        list = new ArrayList<List<Object>>();
        //遍历Excel中所有的sheet
        for (int i = 0; i < work.getNumberOfSheets(); i++) {
            sheet = work.getSheetAt(i);
            String sheetName1 = sheet.getSheetName();

            if (Objects.equals(sheet.getSheetName(), sheetName)){
                int startNum=0;
                //定位表位置
                for (int j = sheet.getFirstRowNum(); j < sheet.getLastRowNum()+1; j++) {
                    row = sheet.getRow(j);
                    if (row!=null){
                        String s = String.valueOf(MaxExcelUtil.getCellValue(row.getCell(0)));
                        if (s.matches(".*"+tableName+".*")){
                            startNum++;
                            break;
                        }
                        else startNum++;
                    }
                    else startNum++;
                }

                //遍历所有的列
                for (int j = startNum+1; j < sheet.getLastRowNum()+1; j++) {
                    row = sheet.getRow(j);
                    List<Object> li = new ArrayList<Object>();
                    if (row==null){return list;}
                    for (int y = row.getFirstCellNum(); y <= row.getLastCellNum(); y++) {
                        cell = row.getCell(y);
                        li.add(MaxExcelUtil.getCellValue(cell));
                    }
                    list.add(li);
                }

            }
        }
        return list;
    }

}
